import os,re
__author__='Leo chen'

def get_login_name():
    "return current user name"
    return os.popen("whoami").read().strip()

def get_host_name():
    "return host name"
    name=os.popen("hostname").read()
    return name.strip()

def get_ps():
    "return Ps info"
    return os.popen("ps auxh|sort").read()

def get_ip(interface):
    "interface= string of interface name. return mac address"
    ifconfig=os.popen("ifconfig").read()
    #search two line that contain interface name
    raw=r"%s.*?\n.*?\n"%interface
    m=re.search(raw,ifconfig)
    if m:
        line=m.group(0)
        ip_re=r"(?<=inet addr:)(\d+)\.(\d+)\.(\d+)\.(\d+)"
        ipaddr=re.search(ip_re,line)
        return ipaddr.group()
    else:
        return "no ip"

def get_mac(interface):
    "interface= string of interface name. return mac address"
    ifconfig=os.popen("ifconfig").read()
    raw=r"%s.*?\n"%interface
    m=re.match(raw,ifconfig)
    if m:
        line=m.group(0)
        #print line
        mac_re=r"""([0-9a-fA-F]{2})(([/\s:-][0-9a-fA-F]{2}){5})"""
        macaddr=re.search(mac_re,line)
        if macaddr:
            return macaddr.group(0)
        else:
            return "no mac"
    else:
        return "no mac"

def cpu_mem_usage(str):
    """count cpu and mem in ps string
    return cpu and mem float percentage"""
    cpu=0
    mem=0
    raw=r".*?\n"
    m=re.finditer(raw,str,re.M)
    for i in m:
        tmp=i.group().split()
        cpu+=float(tmp[2])
        mem+=float(tmp[3])
    if mem>100:
        mem=100
    if cpu>100:
        cpu=100
    return cpu,mem

def get_user_cpu_mem_usage(name,str):
    """
    name= string of username
    str=ps string from get_ps()
    return user's (cpu,mem) usage percentage """
    mem=0
    cpu=0
    raw=r"^%s\s+.*?\n" % name
    m=re.finditer(raw,str,re.M)
    for i in m:
        tmp=i.group().split()
        mem+=float(tmp[3])
        cpu+=float(tmp[2])
    return (cpu,mem)

def get_mem(*type):
    """Get Memory  info by looking in the /proc/meminfo file
    usage:
    total,free,cache= GetMem('MemTotal','MemFree','Cached')"""
    s=os.popen("cat /proc/meminfo").read()
    list=[]
    for str in type:
        total=re.search(r"(?=%s:\s+(\d+))"%str,s)
        if total:
            list.append(total.group(1))
        else:
            list.append("Wrong arg %s"%str)
    return list

def get_disk():
    "return disk info by df -h"
    return os.popen("df -h").read()

def get_cpu():
    """Get Cpu Info in proc/cpuinfo
    return cpu_number,cpu_hz,cpu_type"""
    info=os.popen("cat /proc/cpuinfo").read()
    raw=r"processor.*"
    type=r"model\sname.*"
    number=len(re.findall(raw,info))
    ptype=re.findall(type,info)[0][13:]
    hz=re.findall(r"cpu\sMHz.*",info)[0][11:]
    return  number,hz,ptype

def get_uptime():
    "return system uptime"
    return os.popen("uptime").read()

def get_net_io(interface):
    """interface= interface name
    return network (recv out) info by looking the /proc/net/dev file
    Note: recv and out are string because python 2.2 can not handle
    float properly"""
    matchstr=os.popen("cat /proc/net/dev").read()
    rawstr =r"%s:.*"%interface
    #print rawstr
    #print matchstr
    gup = re.search(rawstr, matchstr,re.M).group()
    all = re.findall(r'\d+', gup)

    return (all[1],all[9])#because all[0]=eth0 so all[1] is receive
                          #number

def reboot():
    "reboot system by using reboot command"
    os.popen("reboot") #TODO: might have privileage problem. should
                       #find a way to check
    return 0



if __name__ =="__main__":
    #print GetLoginName()
    print get_ip("eth0")
    recv,out=get_net_io("eth0")
    print "recv is",recv
    print "out is",out
    ps=get_ps()
    mac=get_mac("eth0")
    print mac
    total,free,cache= get_mem('MemTotal','MemFree','Cached')
    print total,free,cache
